package com.uzai.console.service.takebal.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.User;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.entity.WxpubUser;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.common.utils.Math;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.feign.redpacket.RedPacketCreateAndSendDto;
import com.uzai.console.dto.feign.redpacket.RedPacketGetCardByIdDto;
import com.uzai.console.dto.feign.redpacket.RedPacketQueryResultDto;
import com.uzai.console.dto.feign.redpacket.RedPacketSendByIdDto;
import com.uzai.console.dto.takebal.redpacket.RedPacketIdDto;
import com.uzai.console.dto.takebal.redpacket.RedPacketQuery;
import com.uzai.console.dto.takebal.redpacket.RedPacketSendMsgDto;
import com.uzai.console.entity.Device;
import com.uzai.console.entity.RedPacket;
import com.uzai.console.entity.UserAccDetail;
import com.uzai.console.entity.UserTakeBal;
import com.uzai.console.entity.es.EsWorkWxGroupInfo;
import com.uzai.console.entity.es.EsWxContacts;
import com.uzai.console.mapper.*;
import com.uzai.console.service.CommonService;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.HistoryDataFeignService;
import com.uzai.console.service.feign.RedPacketFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.takebal.RedPacketService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.vo.takebal.redpacket.RedPacketCopyVo;
import com.uzai.console.vo.takebal.redpacket.RedPacketInfoVo;
import com.uzai.console.vo.takebal.redpacket.RedPacketTotalVo;
import com.uzai.console.vo.takebal.redpacket.feign.RedPacketCardVo;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ForkJoinPool;

/***
 * @author liuqi
 * @date 2021年09月01日 19:26
 */
@Service
public class RedPacketServiceImpl extends CommonService implements RedPacketService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;
    @Autowired
    private RedPacketMapper redPacketMapper;
    @Autowired
    private RedPacketFeignService redPacketFeignService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private UserTakeBalMapper userTakeBalMapper;
    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private WxworkUserMapper wxworkUserMapper;
    @Autowired
    private WxpubUserMapper wxpubUserMapper;
    @Autowired
    private UserAccDetailMapper userAccDetailMapper;
    @Autowired
    private HistoryDataFeignService historyDataFeignService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;

    /**
     * 分页查询红包列表列表
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketQuery
     * @return null
     */
    public Page<RedPacketInfoVo> findRedPacketList(RedPacketQuery redPacketQuery){
        //新建返回到页面的LIST对象
        List<RedPacketInfoVo> redPacketInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<RedPacket> page = new Page<>();
        redPacketQuery.convert(page);

        List<RedPacket> redPacketList = null;

        if (super.checkStartEndTimeIsHistoryQuery(redPacketQuery.getCreateTimeStart(), redPacketQuery.getCreateTimeEnd(), null)) {

            String tableSuffix = DateTime.of(redPacketQuery.getCreateTimeEnd() * 1000L).toString("yyMM");
            UzaiRespVo<Page<RedPacket>> listUzaiRespVoRes = historyDataFeignService.pageRedPacketHistory(tableSuffix, redPacketQuery);
            if (listUzaiRespVoRes.getCode() != 200) {
                throw new BusinessException("红包列表查询失败");
            }

            if(listUzaiRespVoRes.getData() != null){
                redPacketList = listUzaiRespVoRes.getData().getRecords();
                page.setTotal(listUzaiRespVoRes.getData().getTotal());
            }

        }
        else {
            redPacketList = redPacketMapper.findByList(page, redPacketQuery);
        }

        if(null != redPacketList){
            for (RedPacket redPacket : redPacketList){
                RedPacketInfoVo redPacketInfoVo = new RedPacketInfoVo();
                BeanUtils.copyProperties(redPacket, redPacketInfoVo);

                //微信昵称
                User user = userService.findUserInfo(redPacketInfoVo.getUserId(), redPacketInfoVo.getDeviceType(), redPacketQuery.getMerId());
                if(user != null){
                    redPacketInfoVo.setNickName(user.getNickName());
                }
                //红包类型
                RedPackTypeEnum redPackTypeEnum = RedPackTypeEnum.getById(redPacketInfoVo.getType());
                if(redPackTypeEnum != null){
                    redPacketInfoVo.setTypeName(redPackTypeEnum.getDesc());
                }
                //红包状态
                RedPackStatusEnum redPackStatusEnum = RedPackStatusEnum.getById(redPacketInfoVo.getStatus());
                if(redPackStatusEnum != null){
                    redPacketInfoVo.setStatusName(redPackStatusEnum.getDesc());
                }

                //查询机器人信息
                Device device = deviceService.findDeviceInfoByDeviceUniqueId(redPacketInfoVo.getDeviceUniqueId(), redPacketInfoVo.getDeviceType(), redPacketQuery.getMerId());
                if(device != null){
                    redPacketInfoVo.setDeviceId(device.getDeviceId());
                    redPacketInfoVo.setDeviceName(device.getDeviceName());
                    redPacketInfoVo.setDeviceRemark(device.getDeviceRemark());

                    //群发红包，需要封装群信息
                    if(StringUtils.isNotBlank(redPacket.getWxGroupId())){
                        redPacketInfoVo.setWxGroupId(redPacket.getWxGroupId());
                        if(redPacket.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())) {//个人微信群
                            //查询微信群
                            String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
                            uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(uzai_wx_contacts, redPacket.getMerId());
                            String groupId = redPacket.getMerId() + "_" + device.getDeviceId() + "_" + redPacket.getWxGroupId();
                            Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, groupId, null);
                            EsWxContacts esWxContacts = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
                            if (esWxContacts != null) {
                                redPacketInfoVo.setWxGroupName(esWxContacts.getNick());
                            }
                        }else{//企业微信群
                            //查询微信群
                            String uzai_workwx_group_info = EsIndexName.UZAI_WORKWX_GROUP_INFO;
                            uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(uzai_workwx_group_info, redPacket.getMerId());
                            String groupId = redPacket.getMerId() + "_" + device.getDeviceId() + "_" + redPacket.getWxGroupId();
                            Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, groupId, null);
                            EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
                            if(esWorkWxGroupInfo != null){
                                redPacketInfoVo.setWxGroupName(esWorkWxGroupInfo.getNickName());
                            }
                        }
                    }

                }

                redPacketInfoVoList.add(redPacketInfoVo);
            }
        }

        //返回到页面分页对象
        Page<RedPacketInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(redPacketInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询红包列表详情
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketIdDto
     * @return null
     */
    public RedPacketInfoVo findRedPacketInfo(RedPacketIdDto redPacketIdDto){
        if(redPacketIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        RedPacket redPacket = redPacketMapper.selectById(redPacketIdDto.getId(), redPacketIdDto.getMerId());

        if(redPacket == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        RedPacketInfoVo redPacketInfoVo =  new RedPacketInfoVo();

        BeanUtils.copyProperties(redPacket, redPacketInfoVo);

        return redPacketInfoVo;
    }

    /**
     * 查询红包总金额
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param query
     * @return null
     */
    public RedPacketTotalVo findTotalMoney(@Param("query") RedPacketQuery query){
        RedPacketTotalVo redPacketTotalVo = new RedPacketTotalVo();
        //历史提现统计
        if (super.checkStartEndTimeIsHistoryQuery(query.getCreateTimeStart(), query.getCreateTimeEnd(), null)) {
            String tableSuffix = DateTime.of(query.getCreateTimeEnd() * 1000L).toString("yyMM");
            UzaiRespVo<BigDecimal> uzaiRespVo = historyDataFeignService.searchRedPacketTotalCount(tableSuffix, query);
            if (uzaiRespVo.getCode() != 200) {
                throw new BusinessException("查询红包列表统计失败");
            }
            if(uzaiRespVo.getData() != null){
                redPacketTotalVo.setTotalMoney(uzaiRespVo.getData().doubleValue());
            }else{
                redPacketTotalVo.setTotalMoney(0.00D);
            }
        } else { //90天内提现统计
            redPacketTotalVo = redPacketMapper.findTotalMoney(query);
        }
        return redPacketTotalVo;
    }

    /**
     * 单个未领取红包发送红包卡片
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketSendMsgDto
     * @return null
     */
    @Transactional
    public void sendCardToOneRedPacketUnReceived(RedPacketSendMsgDto redPacketSendMsgDto){
        if(redPacketSendMsgDto.getId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包ID参数不能为空");
        }

        RedPacket redPacket  = redPacketMapper.selectById(redPacketSendMsgDto.getId(), redPacketSendMsgDto.getMerId());

        if(redPacket == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        if(Tools.getInteger(redPacket.getModel()).intValue() == 1){ //微信红包
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "微信红包不能发送红包卡片");
        }

        if(RedPackStatusEnum.UNCLAIMED.getValue().intValue() != redPacket.getStatus().intValue()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包不是未领取状态");
        }

        //查询用户
        User user = userService.findUserInfo(redPacket.getUserId(), redPacket.getDeviceType(), redPacket.getMerId());
        if(user == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

//        if(StringUtils.isBlank(redPacketSendMsgDto.getMessage())){
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "发送消息为空");
//        }

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(redPacket.getDeviceUniqueId(), redPacket.getDeviceType(), redPacket.getMerId());
        if(device == null) {
            //如果提现记录的机器人不存在，则取会员默认客户端机器人
            device = deviceService.findDeviceInfoByDeviceUniqueId(user.getDeviceUniqueId(), user.getDeviceType(), user.getMerId());
            if (device == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请配置默认客户端");
            }
        }

        //根据红包id发送红包卡片
        RedPacketSendByIdDto redPacketSendByIdDto = new RedPacketSendByIdDto();
        redPacketSendByIdDto.setId(redPacketSendMsgDto.getId());
        UzaiRespVo<Boolean> uzaiRespVo = redPacketFeignService.sendRedpacketById(redPacketSendByIdDto);

        logger.info("--发送红包卡片--para={}, result={}", JSONObject.toJSONString(redPacketSendByIdDto), JSONObject.toJSONString(uzaiRespVo));

        if(uzaiRespVo.getCode() == 200 && uzaiRespVo.getData()){
            //发送文案
            if(StringUtils.isNotBlank(redPacketSendMsgDto.getMessage())){

                //延迟0.5秒再在发送文案
                try {
                    Thread.sleep(500);
                }catch (Exception e){

                }

                //根据红包id查询红包卡片连接
                String redUrl = "";
                RedPacketGetCardByIdDto redPacketGetCardByIdDto = new RedPacketGetCardByIdDto();
                redPacketGetCardByIdDto.setId(redPacketSendMsgDto.getId());
                UzaiRespVo<RedPacketCardVo> uzaiRespVo_redUrl = redPacketFeignService.getRedpacketCardById(redPacketGetCardByIdDto);

                logger.info("--请求红包连接--para={}, result={}", JSONObject.toJSONString(redPacketGetCardByIdDto), JSONObject.toJSONString(uzaiRespVo_redUrl));

                if(uzaiRespVo_redUrl.getCode() == 200 && uzaiRespVo_redUrl.getData() != null){
                    RedPacketCardVo redPacketCardVo = uzaiRespVo_redUrl.getData();
                    redUrl = Tools.getStr(redPacketCardVo.getRedUrl());
                }

                //发送MQ消息
                String message = Tools.getStr(redPacketSendMsgDto.getMessage());
                String nickName = Tools.getStr(user.getNickName());
                Double money = Tools.getDouble(redPacket.getMoney());
                message = message.replace("[昵称]", nickName).replace("[红包金额]", String.valueOf(money)).replace("[提现链接]", redUrl);

                MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
                msgDto.setContent(noticeMsgDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceType(device.getRecvmsgType());
                msgDto.setDeviceUniqueId(redPacket.getDeviceUniqueId());
                msgDto.setMerId(redPacket.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                noticeMsgDto.setContent(message);
                noticeMsgDto.setBizUserId(user.getBizUserId());
                noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                noticeMsgDto.setGroupId(null);
                noticeMsgDto.setNickName(user.getNickName());
                noticeMsgDto.setMsgSource(1);
                noticeMsgDto.setDelay(0);
                noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                noticeMsgPushProducerService.sendMessage(msgDto);
            }
        }else {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }

    }


    /**
     * 作废单个未领取红包
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketIdDto
     * @return null
     */
    @Transactional
    public void invalidToOneRedPacketUnReceived(RedPacketIdDto redPacketIdDto){
        if(redPacketIdDto.getId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包ID参数不能为空");
        }

        RedPacket redPacket  = redPacketMapper.selectById(redPacketIdDto.getId(), redPacketIdDto.getMerId());

        if(redPacket == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        if(RedPackStatusEnum.UNCLAIMED.getValue().intValue() != redPacket.getStatus().intValue()
                && RedPackStatusEnum.SENDING.getValue().intValue() != redPacket.getStatus().intValue()
                && RedPackStatusEnum.SEND_FAIL.getValue().intValue() != redPacket.getStatus().intValue()
        ){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包不是未领取或发送中状态");
        }

        //设置作废状态
        redPacket.setStatus(RedPackStatusEnum.INVALID.getValue());
        redPacket.setUpdateTime(DateUtil.getNowTime());
        int i = redPacketMapper.updateStatus(redPacket);

        if(i != 1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
        }

    }

    /**
     * 作废并偿还单个未领取红包
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketIdDto
     * @return null
     */
    @Transactional
    public void invalidAndRebackToOneRedPacketUnReceived(RedPacketIdDto redPacketIdDto){
        if(redPacketIdDto.getId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包ID参数不能为空");
        }

        RedPacket redPacket  = redPacketMapper.selectById(redPacketIdDto.getId(), redPacketIdDto.getMerId());

        if(redPacket == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        if(RedPackStatusEnum.UNCLAIMED.getValue().intValue() != redPacket.getStatus().intValue()
                && RedPackStatusEnum.SENDING.getValue().intValue() != redPacket.getStatus().intValue()
                && RedPackStatusEnum.SEND_FAIL.getValue().intValue() != redPacket.getStatus().intValue()
        ){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包不是未领取或发送中状态");
        }

        //设置作废状态
        redPacket.setStatus(RedPackStatusEnum.INVALID_REBACK.getValue());
        redPacket.setUpdateTime(DateUtil.getNowTime());
        int i = redPacketMapper.updateStatus(redPacket);

        if(i != 1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
        }

        //偿还金额默认为红包金额
        Double rebackMoney = Tools.getDouble(redPacket.getMoney());
        ////提现红包的话，偿还金额为提现金额
        if(redPacket.getUserTakebalId() != null){
            UserTakeBal userTakeBal = userTakeBalMapper.selectById(redPacket.getUserTakebalId(), redPacket.getMerId());
            if(userTakeBal != null){
                //提现红包的话，则偿还金额为提现金额
                rebackMoney = Tools.getDouble(userTakeBal.getTakeBal());
            }
        }

        //新余额
        double newBalance = 0.00d;
        int newIntegral = 0;
        int now = DateUtil.getNowTime();

        //偿还金额大于0，则修改用户余额
        if(rebackMoney.doubleValue() > 0){
            if (redPacket.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())) { //个人微信用户
                WechatUser wechatUser = wechatUserMapper.selectById(redPacket.getUserId(), redPacket.getMerId());
                if(wechatUser != null){
                    //计算用户余额并修改
                    Double oldBalance = Tools.getDouble(wechatUser.getBalance());
                    newIntegral = Tools.getInteger(wechatUser.getIntegral());
                    //修改余额
                    newBalance = Math.add(oldBalance, rebackMoney);
                    wechatUser.setBalance(newBalance);
                    wechatUser.setUpdateTime(now);
                    int j = wechatUserMapper.updateBalance(wechatUser);
                    if (j != 1) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
                    }
                }
            }else if(redPacket.getDeviceType().equals(DeviceTypeEnum.DT_WORK_WECHAT.getKey())){//企业微信用户
                WxworkUser wxworkUser = wxworkUserMapper.selectById(redPacket.getUserId(), redPacket.getMerId());
                if(wxworkUser != null){
                    //计算用户余额并修改
                    Double oldBalance = Tools.getDouble(wxworkUser.getBalance());
                    newIntegral = Tools.getInteger(wxworkUser.getIntegral());
                    //修改余额
                    newBalance = Math.add(oldBalance, rebackMoney);
                    wxworkUser.setBalance(newBalance);
                    wxworkUser.setUpdateTime(now);
                    int j = wxworkUserMapper.updateBalance(wxworkUser);
                    if (j != 1) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
                    }
                }
            }else if(redPacket.getDeviceType().equals(DeviceTypeEnum.WX_PUB.getKey())) {//公众号用户
                WxpubUser wxpubUser = wxpubUserMapper.selectById(redPacket.getUserId(), redPacket.getMerId());
                if (wxpubUser != null) {
                    //计算用户余额并修改
                    Double oldBalance = Tools.getDouble(wxpubUser.getBalance());
                    newIntegral = Tools.getInteger(wxpubUser.getIntegral());
                    //修改余额
                    newBalance = Math.add(oldBalance, rebackMoney);
                    wxpubUser.setBalance(newBalance);
                    wxpubUser.setUpdateTime(now);
                    int j = wxpubUserMapper.updateBalance(wxpubUser);
                    if (j != 1) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
                    }
                }
            }else{
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "目前还未支持该类型用户");
            }

            //增加账号入账明细
            UserAccDetail wechatUserAccDetail = new UserAccDetail();
            wechatUserAccDetail.setId(IdWorker.getId());
            wechatUserAccDetail.setMerId(redPacket.getMerId());
            wechatUserAccDetail.setUserId(redPacket.getUserId());
            wechatUserAccDetail.setDeviceUniqueId(redPacket.getDeviceUniqueId());
            wechatUserAccDetail.setDeviceType(redPacket.getDeviceType());
            wechatUserAccDetail.setChangeInte(0);
            wechatUserAccDetail.setChangeBal(rebackMoney);
            wechatUserAccDetail.setNewBal(newBalance);
            wechatUserAccDetail.setNewInte(newIntegral);
            wechatUserAccDetail.setType(AccDetailTypeEnum.RED_BALANCE_REBACK.getValue());
            wechatUserAccDetail.setTradeno(redPacket.getTradeno());
            wechatUserAccDetail.setRemark(null);
            wechatUserAccDetail.setCreateTime(now);
            wechatUserAccDetail.setUpdateTime(now);
            int insert = userAccDetailMapper.insert(wechatUserAccDetail);
            if(insert!=1){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
            }
        }
    }

    /**
     * 复制红包地址
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketIdDto
     * @return null
     */
    public RedPacketCopyVo copyRedPacketUrl(RedPacketIdDto redPacketIdDto){
        RedPacketCopyVo redPacketCopyVo = new RedPacketCopyVo();

        if(redPacketIdDto.getId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包ID参数不能为空");
        }

        RedPacket redPacket  = redPacketMapper.selectById(redPacketIdDto.getId(), redPacketIdDto.getMerId());

        if(redPacket == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        if(Tools.getInteger(redPacket.getModel()).intValue() == 1){ //微信红包
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "微信红包不能发送红包卡片");
        }

        //根据红包id查询红包卡片连接
        String redUrl = "";
        RedPacketGetCardByIdDto redPacketGetCardByIdDto = new RedPacketGetCardByIdDto();
        redPacketGetCardByIdDto.setId(redPacketIdDto.getId());
        UzaiRespVo<RedPacketCardVo> uzaiRespVo = redPacketFeignService.getRedpacketCardById(redPacketGetCardByIdDto);
        if(uzaiRespVo != null && uzaiRespVo.getData() != null){
            RedPacketCardVo redPacketCardVo = uzaiRespVo.getData();
            redUrl = redPacketCardVo.getRedUrl();
            redPacketCopyVo.setUrl(redUrl);
        }

        return redPacketCopyVo;
    }

    /**
     * 发送消息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketSendMsgDto
     * @return null
     */
    public void sendMessage(RedPacketSendMsgDto redPacketSendMsgDto){
        if(redPacketSendMsgDto.getId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包ID参数不能为空");
        }

        if(StringUtils.isBlank(redPacketSendMsgDto.getMessage())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "消息不能为空");
        }

        RedPacket redPacket  = redPacketMapper.selectById(redPacketSendMsgDto.getId(), redPacketSendMsgDto.getMerId());

        if(redPacket == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        //查询用户
        User user = userService.findUserInfo(redPacket.getUserId(), redPacket.getDeviceType(), redPacket.getMerId());
        if(user == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(redPacket.getDeviceUniqueId(), redPacket.getDeviceType(), redPacket.getMerId());
        if(device == null) {
            //如果提现记录的机器人不存在，则取会员默认客户端机器人
            device = deviceService.findDeviceInfoByDeviceUniqueId(user.getDeviceUniqueId(), user.getDeviceType(), user.getMerId());
            if (device == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户绑定的机器人id不存在");
            }
        }

        // TODO: 2021/9/4  发送消息
        //发送MQ消息
        MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
        NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
        msgDto.setContent(noticeMsgDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(device.getRecvmsgType());
        msgDto.setDeviceUniqueId(redPacket.getDeviceUniqueId());
        msgDto.setMerId(redPacket.getMerId());
        msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
        noticeMsgDto.setContent(redPacketSendMsgDto.getMessage());
        noticeMsgDto.setBizUserId(user.getBizUserId());
        noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
        noticeMsgDto.setGroupId(null);
        noticeMsgDto.setNickName(user.getNickName());
        noticeMsgDto.setMsgSource(1);
        noticeMsgDto.setDelay(0);
        noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
        noticeMsgPushProducerService.sendMessage(msgDto);

    }

    /**
     * 查询领取结果
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketIdDto
     * @return null
     */
    public void queryResult(RedPacketIdDto redPacketIdDto){
        if(redPacketIdDto.getId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包ID参数不能为空");
        }

        RedPacket redPacket  = redPacketMapper.selectById(redPacketIdDto.getId(), redPacketIdDto.getMerId());

        if(redPacket == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        RedPacketQueryResultDto redPacketQueryResultDto = new RedPacketQueryResultDto();
        redPacketQueryResultDto.setId(redPacket.getId());
        redPacketQueryResultDto.setUserId(redPacket.getUserId());
        UzaiRespVo<Boolean> uzaiRespVo = redPacketFeignService.queryResult(redPacketQueryResultDto);
        logger.info("查询红包支付结果，dto={},result={}",JSONObject.toJSONString(redPacketQueryResultDto),JSONObject.toJSONString(uzaiRespVo));

        if(uzaiRespVo == null ||  uzaiRespVo.getCode() != 200){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, StringUtils.isNotBlank(uzaiRespVo.getMsg())?uzaiRespVo.getMsg(): "查询失败");
        }
    }

}
